﻿using Sgr.Exceptions;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Domain.Tokens
{
    /// <summary>
    /// 临时令牌管理器
    /// </summary>
    public class TemporaryTokenManager : ITemporaryTokenManager
    {
        private readonly ITemporaryTokenRepository _temporaryTokenRepository;

        public TemporaryTokenManager(ITemporaryTokenRepository repository)
        {
            _temporaryTokenRepository = repository;
        }

        /// <summary>
        /// 创建一个新的临时令牌
        /// </summary>
        /// <param name="code">令牌编码</param>
        /// <param name="tokenType">令牌类型</param>
        /// <param name="expirationTime">过期时间</param>
        /// <param name="content">令牌内容</param>
        /// <param name="deviceFingerprint">设备指纹</param>
        /// <param name="userId">用户Id</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<TemporaryToken> CreateAsync(
            string code,
            int tokenType,
            DateTime expirationTime,
            string? content,
            string? deviceFingerprint = null,
            string? userId = null,
            CancellationToken cancellationToken = default)
        {
            Check.StringNotNullOrWhiteSpace(code, nameof(code));

            // 确保令牌编码唯一
            if (await _temporaryTokenRepository.ExistsCodeAsync(code, cancellationToken))
                throw DomainException.ValidationError("令牌编码已存在");

            // 确保过期时间不早于当前时间
            if (expirationTime <= DateTime.UtcNow)
                throw DomainException.ValidationError("过期时间不能早于当前时间");

            return new TemporaryToken(
                code,
                tokenType,
                expirationTime,
                content,
                deviceFingerprint,
                userId);
        }
    }
}